package com.my.study.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 10人开会,人到齐才能开会,做加法,与CountDownLatch相反
 *
 * CyclicBarrier:收集到10个线程才能执行主线程,否则阻塞等待
 */
public class CyclicBarrierDemo {

    private final static int NUM = 10;

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        sinpleCyclicBarrierd();
    }

    /**
     * CyclicBarrier 简单应用
     */
    private static void sinpleCyclicBarrierd() {
        // 条件满足,执行cyclicBarrier参数线程
        CyclicBarrier cyclicBarrier = new CyclicBarrier(NUM,()->{
            System.out.println("所有人到齐,开会!!");
        });
        for (int i = 0; i < NUM; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    System.out.println("第"+ finalI +"同事入会");
                    cyclicBarrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            },"t"+i).start();
        }
    }
}
